using System;
using System.Threading.Tasks;
using Admin.NET.Application.Service.Weather.Dtos;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.RemoteRequest.Extensions;
using IPTools.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Admin.NET.Application.Service;

/// <summary>
/// 天气服务
/// </summary>
[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class WeatherService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly IHttpContextAccessor _httpContextAccessor;

	public WeatherService(IHttpContextAccessor httpContextAccessor)
	{
		_httpContextAccessor = httpContextAccessor;
	}

	[HttpGet("/weather")]
	[AllowAnonymous]
	public async Task<dynamic> GetWeather()
	{
		_httpContextAccessor.HttpContext.GetRemoteIpAddressToIPv4();
		IpInfo ipInfo;
		try
		{
			ipInfo = IpTool.Search("114.222.69.24");
		}
		catch (Exception)
		{
			throw Oops.Bah("获取位置失败");
		}
		if (ipInfo == null)
		{
			throw Oops.Bah("当前网络环境无法获取定位信息的天气");
		}
		string url = "https://wis.qq.com/weather/common?source=pc&weather_type=observe|forecast_24h&province=" + ipInfo.Province + "&city=" + ipInfo.City;
		WeatherOutput res = await url.GetAsAsync<WeatherOutput>();
		if (res.status != 200)
		{
			throw Oops.Bah(res.message);
		}
		return res.data;
	}
}
